package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;

    //获取当前登录（认证）用户的用户名
    @RequestMapping("/getLoginUsername")
    public Result getLoginUsername(){
//        try{
//            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//            String username = user.getUsername();
//            String password = user.getPassword();
//            Collection<GrantedAuthority> authorities = user.getAuthorities();
//            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
//        }catch (Exception e){
//            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
//        }
        Map map=new HashMap();
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user!=null){
            Set<String> auths = AuthorityUtils.authorityListToSet(user.getAuthorities());
            map.put("username",user.getUsername());
            map.put("auths",auths);
            return new Result(true,MessageConstant.GET_USERNAME_SUCCESS,map);
        }
        return new Result(false,MessageConstant.GET_USERNAME_FAIL);
    }


    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    //新增
    @RequestMapping("/add")
    public Result add(@RequestBody com.itheima.pojo.User user, Integer[] roleIds){
        try{
            UUID uuid = UUID.randomUUID();
            String s = uuid.toString();
            String encodePassword = passwordEncoder.encode(s);
            user.setPassword(encodePassword);
            userService.add(user,roleIds);
            return new Result(true,"新增用户信息成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "新增用户信息失败");
        }
    }

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean pageBean){
        return userService.findPage(pageBean);
    }

    //根据id查询用户 用来做编辑页面回显
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            com.itheima.pojo.User user = userService.findById(id);
            return new Result(true, "查询用户信息成功",user);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"查询用户信息失败");
        }
    }

    //用户页面编辑
    @RequestMapping("/edit")
    public Result edit(@RequestBody com.itheima.pojo.User user, Integer[] roleIds){
        try{
            userService.edit(user,roleIds);
            return new Result(true, MessageConstant.EDIT_CHECKGROUP_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_CHECKGROUP_FAIL);
        }
    }

    //删除用户
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {

            com.itheima.pojo.User deleteUser = userService.findById(id);
            Map<String, String> map = new HashMap<>();
            map.put("date", DateUtils.parseDate2String(new Date()));
            map.put("username", deleteUser.getUsername());
            map.put("telephone", deleteUser.getTelephone());
            Jedis jedis = jedisPool.getResource();
            jedis.hmset("deleteUser" + UUID.randomUUID(), map);

            userService.deleteById(id);

            return new Result(true, "删除角色成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"删除角色失败");
        }

    }


    @Reference
    private RoleService roleService;

    //查询所有角色
    @RequestMapping("/findAll")
    public Result findAll(){
        try{
            List<com.itheima.pojo.User> list = userService.findAll();
            return new Result(true, "查找用户成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查找用户失败");
        }
    }

    //重置密码
    @RequestMapping("/resetPassword")
    public Result resetPassword(String newPassword,String id){

        try {
            String encode = passwordEncoder.encode(newPassword);

            com.itheima.pojo.User byId = userService.findById(Integer.parseInt(id));
            byId.setPassword(encode);
            return new Result(true,"密码修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "密码修改失败");
        }


    }

    //批量删除
    @RequestMapping("/deleteMor")
    public Result deleteMor(Integer[] userIds) {
        try {
            Jedis jedis = jedisPool.getResource();
            //把删除的用户信息放入redis中
            for (Integer userId : userIds) {
                com.itheima.pojo.User deleteUser = userService.findById(userId);
                Map<String, String> map = new HashMap<>();
                map.put("date", DateUtils.parseDate2String(new Date()));
                map.put("username", deleteUser.getUsername());
                map.put("telephone", deleteUser.getTelephone());
                jedis.hmset("deleteUser" + UUID.randomUUID(), map);
            }


            //如果删除成功
            if (userService.deleteMor(userIds)) {


                return new Result(true, "批量删除成功");
            } else {
                return new Result(false, "删除用户数大于等于所剩用户");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "批量删除失败");
        }
    }

    //根据RoleId查询UserId
    @RequestMapping("/findUserIdsByRoleId")
    public Result findRoleIdsByUserId(Integer roleId) {
        try {
            List<Integer> list = userService.findRoleIdsByUserId(roleId);
            return new Result(true,"查询角色信息成功",list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询角色信息失败");
        }
    }

    @Autowired
    private JedisPool jedisPool;

    //从redis中查看已经删除的用户信息
    @RequestMapping("/findDeletedUsers")
    public Result findDeletedUsers() {
        List<Map<String, Object>> list = new ArrayList<>();


        Jedis jedis = jedisPool.getResource();
        /*=========================================================*/
        ScanParams scanParams = new ScanParams();
        // 设置每次scan个数
        scanParams.count(120);
        String scanRet = "0";
        List<String> retList = null;
        try {
            do {
                retList = new ArrayList<>();

                ScanResult ret = jedis.scan(scanRet, scanParams.match("deleteUser" + "*"));
                scanRet = ret.getStringCursor();
                retList.addAll(ret.getResult());
            } while (!scanRet.equals("0"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }

        /*=========================================================*/
        List<String> date = null;
        List<String> username = null;
        List<String> telephone = null;
        for (String key : retList) {
            date = jedis.hmget(key, "date");
            username = jedis.hmget(key, "username");
            telephone = jedis.hmget(key, "telephone");
            Map<String, Object> map = new HashMap<>();
            for (String dateString : date) {
                map.put("date", dateString);
            }
            for (String usernameString : username) {
                map.put("username", usernameString);
            }
            for (String telephoneString : telephone) {
                map.put("telephone", telephoneString);
            }
            list.add(map);
        }

        return new Result(true, "成功", list);
    }

    //获取当前用户名所具有角色,权限信息 (权限管理模块的优化:对于用户不具有的权限,不显示对应的功能模块)
    @RequestMapping("/getAuths")
    public Result getAuths() {
        //通过自定义认证类reponse写入到cookie中的用户信息,获取权限信息
        Map map = new HashMap();
        try {
            //获取security框架向cookie中存储的用户对象
            org.springframework.security.core.userdetails.User securityUser = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();//获取框架向浏览器中存储的用户
            //获取用户名称
            String username = securityUser.getUsername();
            Set<String> auths = AuthorityUtils.authorityListToSet(securityUser.getAuthorities());//获取user中权限集合并强转为Set集合
            map.put("auths", auths);
            map.put("username", username);
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.GET_USERNAME_FAIL);
        }
    }
}
